import {ScrollView, View, Text, Image, Input} from '@tarojs/components';
import React, {Component} from 'react';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import {
  AtCurtain,
  AtTextarea,
  AtFloatLayout,
  AtActionSheet,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
} from 'taro-ui';
import 'taro-ui/dist/style/components/float-layout.scss';
import 'taro-ui/dist/style/components/textarea.scss';
import 'taro-ui/dist/style/components/curtain.scss';
import 'taro-ui/dist/style/components/action-sheet.scss';
import 'taro-ui/dist/style/components/modal.scss';
import moment from 'dayjs';
import {connect} from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import rightImg from '@/assets/image/communityService/right.png';
import rangeImg from '@/assets/image/communityService/range.png';
import checkImg from '@/assets/image/communityService/check.png';
import uncheckImg from '@/assets/image/communityService/uncheck.png';
import checkIcon from '@/assets/image/community/c_check.png';
import checkedIcon from '@/assets/image/community/c_checked.png';
import modelClose from '@/assets/image/communityService/modelClose.png';
import curtainClose from '@/assets/image/communityService/curtainClose.png';
import selected from '@/assets/image/communityService/selected.png';
import sucImg from '@/assets/image/communityService/suc.png';

const flowState = (status) => {
  if (status == 0) {
    return '周日';
  } else if (status == 1) {
    return '周一';
  } else if (status == 2) {
    return '周二';
  } else if (status == 3) {
    return '周三';
  } else if (status == 4) {
    return '周四';
  } else if (status == 5) {
    return '周五';
  } else if (status == 6) {
    return '周六';
  }
};

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      remarks: '',
      cancelList: [
        {
          label: '信息填写错误',
        },
        {
          label: '预约当日没有时间',
        },
        {
          label: '不想回收了',
        },
        {
          label: '其他原因',
        },
      ],
      value: '',
    };
  }

  componentDidMount() {
    let {
      actions: {action},
    } = this.props;

    this.props.actions.init();
    let {type, orderId} = getCurrentInstance().router.params;
    if (type == 'edit') {
      Taro.setNavigationBarTitle({
        title: '修改/取消订单',
      });
      action.commonChange('main.orderId', orderId);
    }
    action.commonChange('main.type', type);
  }

  componentDidShow() {
    let {
      actions: {action},
    } = this.props;
    if (Taro.getStorageSync('Select delivery address')) {
      action.commonChange('main.address', Taro.getStorageSync('Select delivery address'));
    }
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  handleChange(value) {
    this.setState({remarks: value});
  }

  onClose() {
    let {
      main: {},
      actions: {action},
    } = this.props;
    action.commonChange('main.successModel', false);
  }

  async addClick() {
    let {
      main: {
        dateTime,
        remarks,
        list,
        listSelected,
        dateModel,
        checked,
        daysArr,
        timeArr,
        daysSelected,
        timeSelected,
        remarksModel,
        successModel,
        address,
      },
      actions: {action},
    } = this.props;
    if (listSelected == null) {
      Taro.showToast({
        title: '请选择预估本数！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (JSON.stringify(address) == '{}') {
      Taro.showToast({
        title: '请选择地址信息！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (timeSelected == null) {
      Taro.showToast({
        title: '请选择上门时间！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (!checked) {
      Taro.showToast({
        title: '请勾选用户协议！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    action.whaleorderAdd();
  }

  async editClick() {
    let {
      main: {
        dateTime,
        remarks,
        list,
        listSelected,
        dateModel,
        checked,
        daysArr,
        timeArr,
        daysSelected,
        timeSelected,
        remarksModel,
        successModel,
        address,
      },
      actions: {action},
    } = this.props;
    if (listSelected == null) {
      Taro.showToast({
        title: '请选择预估本数！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (JSON.stringify(address) == '{}') {
      Taro.showToast({
        title: '请选择地址信息！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (timeSelected == null) {
      Taro.showToast({
        title: '请选择上门时间！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    action.whaleorderEdit();
  }

  render() {
    let {
      main: {
        dateTime,
        remarks,
        list,
        listSelected,
        dateModel,
        checked,
        daysArr,
        timeArr,
        daysSelected,
        timeSelected,
        remarksModel,
        successModel,
        address,
        type,
        cancelModel,
        cancellationOptions, //取消类型
        cancellationReason, //取消原因
      },
      actions: {action},
    } = this.props;
    let {cancelList} = this.state;
    return (
      <View className="packageDClothingReservation">
        <ScrollView scrollY className="scrollView">
          <View className="main">
            <View className="titleBox">
              <Text className="title">地址信息</Text>
              <View
                className="rangeImgBox"
                onClick={(e) => {
                  e.stopPropagation();
                  Taro.navigateTo({
                    url: '/pages/package-D/cityLimits/index',
                  });
                }}
              >
                <Image className="rangeImg" src={rangeImg} mode="widthFix" />
                <Text className="f24">上门范围</Text>
              </View>
            </View>
            <View
              className="addressBox"
              onClick={() => {
                Taro.navigateTo({
                  url: '/pages/package-D/addressSelect/index',
                });
              }}
            >
              {JSON.stringify(address) == '{}' ? (
                <View className="address">
                  <Text className="name">请先设置地址信息</Text>
                  <Image className="rightImg" src={rightImg} mode="widthFix" />
                </View>
              ) : (
                <>
                  <View className="name">
                    {address?.consigneeName} {address?.consigneeNumber}
                  </View>
                  <View className="address">
                    <Text className="info">{address?.addressInfo}</Text>
                    <Image className="rightImg" src={rightImg} mode="widthFix" />
                  </View>
                </>
              )}
            </View>
            <View className="titleBox">
              <Text className="title">预约信息</Text>
              <View></View>
            </View>
            <View
              className="formBox"
              onClick={(e) => {
                e.stopPropagation();
                action.commonChange('main.dateModel', true);
              }}
            >
              <Text className="input">上门时间</Text>
              <View className="row">
                <Text className="f28">
                  {daysSelected != null && timeSelected != null
                    ? daysArr[daysSelected]?.name + '    ' + timeArr[timeSelected]?.name
                    : '请选择时间'}
                </Text>
                <Image className="rightImg" src={rightImg} mode="widthFix" />
              </View>
            </View>
            {type == 'add' && (
              <View
                className="formBox"
                onClick={(e) => {
                  e.stopPropagation();
                  this.setState({remarks: remarks});
                  action.commonChange('main.remarksModel', true);
                }}
              >
                <Text className="input">备注(选填)</Text>
                <View className="row">
                  <Text className="f28">{remarks ? remarks : '当前无备注'}</Text>
                  <Image className="rightImg" src={rightImg} mode="widthFix" />
                </View>
              </View>
            )}
            <View className="titleBox">
              <Text className="title">预估重量</Text>
              <Text className="tRight">预估重量仅供参考，以实际重量为准</Text>
            </View>
            <View className="listBox">
              {list.map((item, index) => (
                <View
                  className="f1"
                  onClick={(e) => {
                    e.stopPropagation();
                    action.commonChange('main.listSelected', index);
                  }}
                >
                  <View className={listSelected == index ? 'item-a' : 'item'}>
                    <Text className={listSelected == index ? 'name-a' : 'name'}>{item.name}</Text>
                    <Text className={listSelected == index ? 'desc-a' : 'desc'}>{item.desc}</Text>
                  </View>
                </View>
              ))}
            </View>
          </View>
        </ScrollView>
        <View className="bottom">
          {type == 'edit' && (
            <View className="flexEnd">
              <View
                className="cancelBtn"
                onClick={() => {
                  action.commonChange('main.cancelModel', true);
                }}
              >
                取消订单
              </View>
              <View
                className="editBtn"
                onClick={() => {
                  this.editClick();
                }}
              >
                确定修改并提交
              </View>
            </View>
          )}
          {type == 'add' && (
            <View
              className="btn_box"
              onClick={() => {
                this.addClick();
              }}
            >
              <Text className="btn-release">确认提交</Text>
            </View>
          )}
          {type == 'add' && (
            <View
              className="checkBox"
              onClick={(e) => {
                e.stopPropagation();
                action.commonChange('main.checked', !checked);
              }}
            >
              <Image className="checkImg" src={checked ? checkImg : uncheckImg} mode="widthFix" />
              <Text className="text">
                请仔细阅读
                <Text
                  className="agreement"
                  onClick={(e) => {
                    e.stopPropagation();
                    Taro.navigateTo({
                      url: '/pages/package-D/recyclingAgreement/index',
                    });
                  }}
                >
                  《旧衣服回收协议》
                </Text>
              </Text>
            </View>
          )}
        </View>
        <AtFloatLayout isOpened={dateModel} className="dateModel">
          <View className="titleBox">
            <View></View>
            <View className="title">选择上门时间</View>
            <Image
              onClick={(e) => {
                e.stopPropagation();
                action.commonChange('main.dateModel', false);
              }}
              className="closeImg"
              src={modelClose}
              mode="widthFix"
            />
          </View>
          <View className="modelListBox">
            <ScrollView scrollY className="left">
              {daysArr.length > 0 &&
                daysArr.map((item, index) => (
                  <View
                    onClick={(e) => {
                      e.stopPropagation();
                      action.commonChange('main.daysSelected', index);
                      action.commonChange('main.timeSelected', null);
                    }}
                  >
                    <View className={daysSelected == index ? 'item-a' : 'item'}>
                      <Text className={daysSelected == index ? 'name-a' : 'name'}>
                        {index == 0
                          ? '当天'
                          : `${flowState(moment(item?.name).day())} (${moment(item?.name).month()}/${moment(
                              item?.name,
                            ).date()})`}
                      </Text>
                    </View>
                  </View>
                ))}
            </ScrollView>
            <ScrollView scrollY className="right">
              {timeArr.length > 0 &&
                timeArr.map((item, index) => (
                  <View
                    onClick={(e) => {
                      e.stopPropagation();
                      action.commonChange('main.timeSelected', index);
                      action.commonChange('main.dateModel', false);
                    }}
                  >
                    <View className="item">
                      <Text className="name">{item?.name}</Text>
                      {timeSelected == index && <Image className="selected" src={selected} mode="widthFix" />}
                    </View>
                  </View>
                ))}
            </ScrollView>
          </View>
        </AtFloatLayout>
        <AtFloatLayout isOpened={remarksModel} className="remarksModel">
          <View className="titleBox">
            <View></View>
            <View className="title">填写备注</View>
            <Image
              onClick={(e) => {
                e.stopPropagation();
                action.commonChange('main.remarksModel', false);
              }}
              className="closeImg"
              src={modelClose}
              mode="widthFix"
            />
          </View>
          <AtTextarea
            className="remarks"
            value={this.state.remarks}
            onChange={this.handleChange.bind(this)}
            maxLength={15}
            placeholder="请填写留言，最多15个字"
          />
          <View className="btn_box">
            <Text
              className="btn-release"
              onClick={() => {
                action.commonChange('main.remarks', this.state.remarks);
                action.commonChange('main.remarksModel', false);
              }}
            >
              确认
            </Text>
          </View>
        </AtFloatLayout>
        <AtCurtain isOpened={successModel} onClose={this.onClose.bind(this)} className="successModel">
          <View className="main">
            <View className="topBox">
              <View className="row">
                <Image className="sucImg" src={sucImg} mode="widthFix" />
                <Text className="text">预约成功</Text>
              </View>
              <Text className="f24">您的订单已提交给商家</Text>
            </View>
            <View className="bottomBox">
              <Text className="text">商家稍后将和您电话沟通、确定具体服务需求，以便为您优选服务人员，请耐心等待</Text>
              <View
                className="btn"
                onClick={(e) => {
                  action.commonChange('main.successModel', false);
                  Taro.removeStorageSync('Select delivery address');
                  Taro.navigateTo({
                    url: '/pages/package-D/equityOrders/index',
                  });
                }}
              >
                查看/修改订单
              </View>
              <Text
                className="back"
                onClick={(e) => {
                  action.commonChange('main.successModel', false);
                  Taro.removeStorageSync('Select delivery address');
                  Taro.switchTab({url: '/pages/index/index'});
                }}
              >
                回首页
              </Text>
            </View>
          </View>
        </AtCurtain>
        {/* 请选择取消原因 */}
        <AtActionSheet
          isOpened={cancelModel}
          onClose={() => {
            action.commonChange('main.cancelModel', false);
          }}
          onCancel={() => {
            action.commonChange('main.cancelModel', false);
          }}
        >
          <View className="cancelModel">
            <View className="row-box">
              <Text className="title">您正在删除/取消预约</Text>
              <Image
                className="close"
                src={modelClose}
                mode="widthFix"
                onClick={(e) => {
                  action.commonChange('main.cancelModel', false);
                }}
              />
            </View>
            <View className="list-box">
              {cancelList.map((item, index) => {
                return (
                  <View
                    className="row"
                    key={index}
                    onClick={(e) => {
                      action.commonChange('main.cancellationReason', '');
                      action.commonChange('main.cancellationOptions', index);
                    }}
                  >
                    <Text className="label">{item.label}</Text>
                    <Image
                      className="check"
                      src={cancellationOptions == index ? checkedIcon : checkIcon}
                      mode="widthFix"
                    />
                  </View>
                );
              })}
              {cancellationOptions == 3 && (
                <AtTextarea
                  className="textarea"
                  value={cancellationReason}
                  onChange={(e) => {
                    action.commonChange('main.cancellationReason', e?.substring?.(0, 300));
                  }}
                  maxLength={300}
                  placeholder="请输入取消原因(选填)"
                  placeholderStyle="color:#BFBFBF;font-size:14px"
                />
              )}
            </View>
            <View
              className="bottomBtn"
              onClick={(e) => {
                action.cancelWhaleorder();
              }}
            >
              确认取消
            </View>
          </View>
        </AtActionSheet>
      </View>
    );
  }
}
